package com.qike.duola.cors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/****
 * @description：跨域请求访问设置
 *
 * @author fanghuaiming
 * @data Created in 2019/6/29 3:21 PM
 *
 */
@Slf4j
@Configuration
public class CorsConfig extends HandlerInterceptorAdapter {

    /**
     * 临时配置 携带cookie就不能使用通配符 * /此项目使用无状态Token，所以无所谓
     */
//    @Value("${ACCESS_CONTROLALLOW_ORIGIN}")
//    private String ACCESS_CONTROLALLOW_ORIGIN;
 
    /*@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //添加跨域CORS
        response.setHeader("Access-Control-Allow-Origin", ACCESS_CONTROLALLOW_ORIGIN);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers",
                "Authorization,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Sioo-Client-Token");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        return true;
    }*/

    /**
     * @Description: 跨域配置
     * @Param:
     * @return:
     * @Author: fanghuaiming
     * @Date: 10:03 AM 2019/8/6
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "86400");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,token,Authorization");
        // 如果是OPTIONS
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
//            System.out.println("123123");
            response.setStatus(HttpStatus.OK.value());
            log.debug("跨域配置requestURI:{}",request.getRequestURI());
            log.debug("跨域配置method:{}",request.getMethod());
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}